#include "stdafx.h"
#include "ModuleTreeWindow.h"
#include "resource.h"

#pragma comment(lib, "comctl32.lib")

CModuleTreeWindow::CModuleTreeWindow()
{
}

CModuleTreeWindow::~CModuleTreeWindow()
{
}
	
bool CModuleTreeWindow::Create(HINSTANCE hInstance,HWND hParentWnd,UINT nID)
{
	RECT rcWindow = {0, 0, 10, 10};

	if( !CreateWindowBase( WS_EX_STATICEDGE, WC_TREEVIEW, NULL, WS_VISIBLE | WS_CHILD | TVS_HASLINES | TVS_HASBUTTONS | TVS_LINESATROOT, rcWindow, hParentWnd, (HMENU)nID, hInstance))
		return false;

	m_hImageList = ImageList_Create( 16, 16, ILC_COLOR8 | ILC_MASK, 0, 0);

	ImageList_AddIcon( m_hImageList, (HICON)LoadIcon( hInstance, MAKEINTRESOURCE( IDI_MODULE)));
	ImageList_AddIcon( m_hImageList, (HICON)LoadIcon( hInstance, MAKEINTRESOURCE( IDI_MODULEVERSION)));

//	DeleteObject( icon);

	TreeView_SetImageList( m_hWnd, m_hImageList, TVSIL_NORMAL);
	
	return true;
}

void CModuleTreeWindow::Release()
{
	ImageList_Destroy( m_hImageList);
	
	m_TreeItemMap.clear();
}

void CModuleTreeWindow::DeleteAllItems()
{
	TreeView_DeleteAllItems( m_hWnd);
	m_TreeItemMap.clear();
}

HTREEITEM CModuleTreeWindow::InsertItem( LPCTSTR szItem,HTREEITEM hParent,DWORD dwParam,int imageIndex)
{
	TV_INSERTSTRUCT insert;
	ZeroMemory( &insert, sizeof( TV_INSERTSTRUCT));
	
	insert.hParent = hParent;
	insert.item.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
	insert.item.cchTextMax = sizeof( szItem);
	insert.item.pszText = (char*)szItem;
	insert.item.lParam = dwParam;
	insert.item.iImage = imageIndex;
	insert.item.iSelectedImage = imageIndex;

	HTREEITEM hItem = (HTREEITEM)TreeView_InsertItem( m_hWnd, &insert);

	if( hItem)
		m_TreeItemMap.insert( MAP_HTREEITEM_BY_PARAM::value_type( dwParam, hItem));

	return hItem;
}

HTREEITEM CModuleTreeWindow::FindItem(DWORD dwParam)
{
	MAP_HTREEITEM_BY_PARAM::iterator it;
	it = m_TreeItemMap.find( dwParam);
	if( it == m_TreeItemMap.end())
		return NULL;

	return (*it).second;
}

sModule*			CModuleTreeWindow::GetModule(HTREEITEM hItem)
{
	if( TreeView_GetParent( m_hWnd, hItem) != NULL)
		return NULL;

	TVITEMEX item;
	item.mask = TVIF_HANDLE | TVIF_PARAM;
	item.hItem = hItem;
	item.lParam = 0;

	if( !TreeView_GetItem( m_hWnd, &item))
		return NULL;

	return (sModule*)item.lParam;
}

sModuleVersion*	CModuleTreeWindow::GetModuleVersion(HTREEITEM hItem)
{
	if( TreeView_GetParent( m_hWnd, hItem) == NULL)
		return NULL;

	TVITEMEX item;
	item.mask = TVIF_HANDLE | TVIF_PARAM;
	item.hItem = hItem;
	item.lParam = 0;

	if( !TreeView_GetItem( m_hWnd, &item))
		return NULL;

	return (sModuleVersion*)item.lParam;
}
